<template>
  <div class="home">
    <div class="main-content">
      <!-- 英雄区域 -->
      <section class="hero">
        <div class="hero-content">
          <h1 class="hero-title">{{ siteTitle }}</h1>
          <p class="hero-subtitle">{{ siteSubtitle }}</p>
          <div class="hero-actions">
            <router-link to="/" class="btn btn-primary">浏览文章</router-link>
            <router-link to="/about" class="btn btn-secondary">了解更多</router-link>
          </div>
        </div>
      </section>
      <!-- 最新文章 -->
      <section class="latest-posts">
        <h2 class="section-title">最新文章</h2>
        <div class="posts-grid">
          <article 
            v-for="post in latestPosts" 
            :key="post.id" 
            class="post-card"
            @click="viewPost(post.id)"
          >
            <div class="post-image">
              <img :src="getCoverUrl(post.coverImage)" :alt="post.title" @error="onImgError" />
            </div>
            <div class="post-content">
              <div class="post-meta">
                <span class="post-date">{{ formatDate(post.createdAt || post.date) }}</span>
                <span class="post-category">{{ post.category }}</span>
              </div>
              <h3 class="post-title">{{ post.title }}</h3>
              <p class="post-excerpt">{{ post.excerpt }}</p>
              <div class="post-tags">
                <span 
                  v-for="tag in (Array.isArray(post.tags) ? post.tags : (post.tags ? post.tags.split(',') : []))" 
                  :key="tag" 
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>
            </div>
          </article>
        </div>
      </section>
    </div>
    <aside class="sidebar">
      <div class="author-card">
        <img class="author-avatar" :src="user.avatar || 'https://picsum.photos/100/100?random=author'" alt="作者头像" />
        <h3 class="author-name">{{ user.username || '未登录' }}</h3>
        <p class="author-bio">{{ user.bio || '前端开发工程师，热爱技术与分享。' }}</p>
      </div>
      <div class="sidebar-section">
        <h4>博客统计</h4>
        <ul class="blog-stats">
          <li>文章数：{{ blogStats.totalPosts }}</li>
          <li>分类数：{{ blogStats.totalCategories }}</li>
          <li>标签数：{{ blogStats.totalTags }}</li>
        </ul>
      </div>
      <div class="sidebar-section">
        <h4>标签云</h4>
        <div class="tag-cloud">
          <span v-for="tag in Array.from(tags)" :key="tag" class="tag">{{ tag }}</span>
        </div>
      </div>
    </aside>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import type { User, Article, BlogStats } from './types'
import { fetchProfile, fetchArticles, formatDate, getCoverUrl, onImgError } from './service'

const router = useRouter()
const siteTitle = ref('')
const siteSubtitle = ref('')
const user = ref<User>({})
const articles = ref<Article[]>([])
const categories = ref(new Set<string>())
const tags = ref(new Set<string>())

const fetchData = async () => {
  try {
    // 获取用户资料
    const userData = await fetchProfile()
    user.value = userData
    siteTitle.value = userData.siteTitle || '欢迎来到我的博客'
    siteSubtitle.value = userData.siteSubtitle || '分享技术、生活和思考的地方'
  } catch (error) {
    siteTitle.value = '欢迎来到我的博客'
    siteSubtitle.value = '分享技术、生活和思考的地方'
  }

  try {
    // 获取文章数据
    const data = await fetchArticles()
    articles.value = data
    categories.value = new Set(data.map((a: { category?: string }) => a.category).filter((cat): cat is string => Boolean(cat)))
    tags.value = new Set(data.flatMap((a: { tags?: string[] | string }) => (a.tags ? (Array.isArray(a.tags) ? a.tags : a.tags.split(',')) : [])).map((t: string) => t.trim()).filter(Boolean))
  } catch (error) {
    console.error('获取文章失败:', error)
  }
}

onMounted(fetchData)

const latestPosts = computed(() => articles.value.slice(0, 6))

const blogStats = computed((): BlogStats => ({
  totalPosts: articles.value.length,
  totalCategories: categories.value.size,
  totalTags: tags.value.size
}))

const viewPost = (id: number) => {
  router.push(`/post/${id}`)
}
</script>

<style scoped>
@import './style.css';
</style> 